package com.baozheyangken.ai_learn.interceptor;

import com.baozheyangken.ai_learn.context.BaseContext;
import com.baozheyangken.ai_learn.properties.JwtProperties;
import com.baozheyangken.ai_learn.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //String token = request.getHeader(jwtProperties.getUserTokenName());
        String authHeader = request.getHeader("Authorization");
        String token = null;

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else
            token = request.getHeader(jwtProperties.getUserTokenName());

        log.info("jwt校验:{}", token);

        if (token == null) {
            response.setStatus(401);
            return false;
        }

        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties
                    .getUserSecretKey()
                    .getBytes(StandardCharsets.UTF_8), token);
            Integer userId = (Integer) claims.get("userId");
            log.info("当前用户id:{}", userId);
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }
}
